package com.ziyueyuwen.xiniao.spi.impl;

import com.alibaba.fastjson.JSON;
import com.ziyueyuwen.xiniao.bean.homework.AnswerData;
import com.ziyueyuwen.xiniao.bean.homework.ItemData;
import com.ziyueyuwen.xiniao.bean.homework.QuestionInfo;
import com.ziyueyuwen.xiniao.spi.QuestionTypeService;

import java.util.List;

import static com.ziyueyuwen.xiniao.enums.QuestionTypeEnum.CONNECTION_PROBLEM_2;

/**
 * 新版连线题 一对多
 *
 * @author jun 2018/12/18.
 */
public class ConnectionProblem2Impl implements QuestionTypeService {

    @Override
    public void saveAnswer(String answerData, Integer questionNum, QuestionInfo questionInfo, List<AnswerData> answerDataList) {
        if (questionInfo.getQuestionType() == CONNECTION_PROBLEM_2) {
            answerData = answerData.toUpperCase();
            List<String> dataList = JSON.parseArray(answerData, String.class);
            AnswerData answerDataBean = new AnswerData();
            answerDataBean.setTotalScore(getTotalScore(questionInfo.getNewRightDataList()));
            answerDataBean.setQuestionType(CONNECTION_PROBLEM_2);
            answerDataBean.setCorrectScore(getCorrectScore(dataList, questionInfo));
            answerDataBean.setObjectiveAnswerList(dataList);
            if (answerDataList.size() < questionNum) {
                answerDataList.add(answerDataBean);
            } else {
                answerDataList.set(questionNum - 1, answerDataBean);
            }
        }
    }

    /**
     * 计算本题得分
     *
     * @param studentAnswerList String
     * @param questionInfo      QuestionInfo
     * @return Integer
     */
    private Integer getCorrectScore(List<String> studentAnswerList, QuestionInfo questionInfo) {
        int score = 0;
        List<ItemData> correctAnswerList = questionInfo.getNewRightDataList();
        for (int i = 0; i < correctAnswerList.size() && i < studentAnswerList.size(); i++) {
            int idx = Integer.valueOf(studentAnswerList.get(i));
            ItemData itemData = correctAnswerList.get(i);
            if (idx == itemData.getLeft()) {
                score += itemData.getScore();
            }
        }
        return score;
    }

    /**
     * 计算本题总分
     *
     * @param list List
     * @return Integer
     */
    private Integer getTotalScore(List<ItemData> list) {
        int totalScore = 0;
        for (ItemData i : list) {
            totalScore += i.getScore();
        }
        return totalScore;
    }

}
